import { createContext, PropsWithChildren, ReactNode, useContext } from 'react'

interface KeepAliveLayoutProps extends PropsWithChildren {
  keepPaths: Array<string | RegExp>
  keepElements?: Record<string, ReactNode>
  dropByPath?: (path: string) => void
}

type KeepAliveContextType = Omit<Required<KeepAliveLayoutProps>, 'children'>

const keepElements: KeepAliveContextType['keepElements'] = {}

const KeepAliveContext = createContext<KeepAliveContextType>({
  keepPaths: [],
  keepElements,
  dropByPath: (path: string) => {
    keepElements[path] = null
  }
})

const KeepAliveLayout = (props: KeepAliveLayoutProps) => {
  const { keepPaths, ...other } = props
  const { keepElements, dropByPath } = useContext(KeepAliveContext)

  return <KeepAliveContext.Provider value={{ keepPaths, keepElements, dropByPath }} {...other} />
}

export { KeepAliveContext }

export default KeepAliveLayout
